package drds.plus.executor.cursor.cursor.impl.sort;

import drds.plus.executor.cursor.cursor.ISortingCursor;
import drds.plus.executor.row_values.RowValues;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.abstract_syntax_tree.expression.order_by.OrderBy;
import drds.plus.util.GeneralUtil;

import java.util.List;

/**
 * 去重操作
 */
public class DistinctCursor extends SortedMergeCursors {
    /**
     * 仅仅一个游标
     */
    public DistinctCursor(ISortingCursor sortingCursor, List<OrderBy> distinctOrderbyList) throws RuntimeException {
        super(sortingCursor, false);
        this.cursor = sortingCursor;
        this.orderByList = distinctOrderbyList;
    }

    public String toStringWithInden(int inden) {
        String tabTittle = GeneralUtil.getTab(inden);
        String tabContent = GeneralUtil.getTab(inden + 1);
        StringBuilder sb = new StringBuilder();
        GeneralUtil.printlnToStringBuilder(sb, tabTittle + "DistinctCursor ");
        GeneralUtil.printAFieldToStringBuilder(sb, "addOrderByItemAndSetNeedBuild", this.orderByList, tabContent);
        sb.append(tabContent).append("cursor:").append("\n");
        sb.append(cursor.toStringWithInden(inden + 1));
        return sb.toString();
    }

    public RowValues next() throws RuntimeException {
        RowValues next = null;
        while ((next = (cursor.next())) != null) {
            if (current == null) {
                break;
            }
            super.initComparator(orderByList, next.getParentCursorMetaData());
            int n = rowDataComparator.compare(next, current);
            if (n != 0) {
                break;
            }
            next = null;
        }
        this.current = Utils.fromRowDataToArrayRowData(next);
        return next;
    }

}
